package com.apobates.forum.core.security.exposure.config.supply;

import com.apobates.forum.core.entity.BoardConfig;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.core.security.exception.StrategyException;
import com.apobates.forum.core.security.exposure.config.ConfigPlugBiPredicate;
import com.apobates.forum.core.security.strategy.StrategyMode;
import com.apobates.forum.member.entity.Member;
import java.util.function.BiPredicate;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**
 * 话题发布不间断操作补充策略
 * 
 * @author xiaofanku
 * @since 20200806
 */
public final class BoardConfigInterruptStrategy implements ConfigPlugBiPredicate<BoardConfig, Member>{
    private final Supplier<Stream<Topic>> recentTopices;
    
    public BoardConfigInterruptStrategy(Supplier<Stream<Topic>> recentTopices) {
        this.recentTopices = recentTopices;
    }
    
    @Override
    public Supplier<BiPredicate<BoardConfig, Member>> condition() {
        return ()->(BoardConfig entityConfig, Member culpritor)->{
            int wmiSize = entityConfig.getWriteMinInterrupt();
            long member = culpritor.getId();
            
            if (wmiSize > 0) {
                long statsData = recentTopices.get().filter(t -> t.getMemberId() == member).count();
                if (statsData >= wmiSize) {
                    throw new StrategyException("版块连续操作次数设置导致发贴被中断");
                }
            }
            return true;
        };
    }
    
    @Override
    public StrategyMode[] allowModes(){
        return new StrategyMode[]{StrategyMode.WRITE};
    }
}